//
//  KSBlockItem.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/9/5.
//  Copyright © 2023 zwb. All rights reserved.
//  滑块

import UIKit

class KSBlockItem: KSFormHItem {
    // MARK: - 懒加载 lazy
    private lazy var blockX:UISegmentedControl = {
        let v = UISegmentedControl()
          return v
    }()
    
    private var oriTitles:[SegmenttData] = []
    var blockValueChangeClo:((SegmenttData)->())?
    convenience init(title:String,appearance: KSFormBaseAppear? = KSFormBaseAppear()) {
        self.init(title: title, appearance: appearance,type:.switchx)
        self.assistBtn.isHidden = true
        self.addSubview(blockX)
        blockX.snp.makeConstraints { make in
             make.height.equalTo(32)
            make.right.equalTo(self).offset(-(self.appearance.arrowTrailing + 5))
            make.width.equalTo(KSGlobal.screenW - 150)
            make.centerY.equalTo(self)
        }
        blockX.addSegmentChangeClosure { segment in
            if let clo = self.blockValueChangeClo {
                clo(self.oriTitles[segment.selectedSegmentIndex])
            }
        }
   
        
      }
    func setBlockValue(nm:String) {
        
      if let ind =  self.oriTitles.getIndexFor { segData in
            segData.nm == nm
      } {
          self.blockX.selectedSegmentIndex = ind
      } else {
          self.blockX.selectedSegmentIndex = -1

      }
 
    }
 
   
    //设置滑块
    func setBlockTitles(_ titles:[SegmenttData]) {
        
        
        
        
        if titles != oriTitles {
            self.oriTitles = titles
            self.blockX.removeAllSegments()
            for item in titles.reversed() {
                self.blockX.insertSegment(withTitle: item.nm.unwrap, at: 0, animated: true)
            }
            self.blockX.selectedSegmentIndex = 0
        }
        
    }
    // 获取内容 用于判空等
    override func contValue() -> String {
        if blockX.selectedSegmentIndex < self.oriTitles.count && blockX.selectedSegmentIndex != -1 {
            return self.oriTitles[blockX.selectedSegmentIndex].nm.unwrap
        } else {
            return ""
        }
        
    }
    
}
struct SegmenttData:Equatable {
    var id:String?
    var nm:String?
    static func == (lhs: SegmenttData, rhs: SegmenttData) -> Bool {
       return (lhs.id == rhs.id && lhs.nm == rhs.nm)
    }
}
